import datetime
import json
from calendar import monthrange
from pprint import pprint
from random import randint
from uuid import uuid4

from django.core.cache import cache
from django.db.models import Value, Sum, F, Q
from django.db.models.functions.datetime import (
    TruncDay,
)
from django.test import RequestFactory, TestCase, Client
from rest_framework import status

from jqexception.jqexecption import (
    RightErr,
    ValueErr,
)
from jqgame.basegame import GameType
from jqgame.raffle import weight_random
from jqpackage.models import UserPackageGoods
from quanjushang.models import QuanjushangSonGame, QuanjushangGame
from quanjushang.ser import QuanjushangGamSer
from warehouse.models import JuqiGood
from wxcloudrun.models import get_web_settings
from wxcloudrun.ser import WebSettingsSerializer
from wxcloudrun.views import order_uuid
from wxuser.models import (
    Users,
    UserRefinedOrder,
    UserOrder,
    UserStoredMoneyRecord,
    UserRechargeOrder,
    OrderState,
    UserRechargeType,
    UserHunJingRecord,
    UserScoreRecord,
    UserState,
)
from wxuser.serializers import (
    UserSerializer,
    UserResultSerializer,
    get_detail_UserPackage,
    calculate_UserPackage_sum_price_by_date,
)
from .common.utlis import (
    get_web_settings_statistical_exclude_user_uuid_list,
    get_web_settings_statistical_exclude_user_uid_list,
)
from .constants import Constants
from .errer import GameRuleNullErr
from .models import (
    FinanceType,
    JuqiAdmin,
    get_game_finance,
    get_wxuser_finance,
    UserWithdraw,
    Finance,
    update_finnce_profit,
    get_wxuser_recharge_withdraw_finance,
)
from .serializers import FinanceSerializer


# Create your tests here.
class JuqiAdminLoginTest(TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.c = Client()
        self.factory = RequestFactory()

    # python manage.py test juqiadmin.tests.JuqiAdminTest.test_login
    def test_login_1(self):
        r = self.c.post(
            "/api/admin/login",
            {"user": "admin", "password": "admin123"},
            content_type="application/json",
        )

        d = json.loads(r.content)
        print(self.c.session.items())
        self.assertEqual(len(self.c.session.get("login_token", "")), 64)
        self.assertEqual(d["code"], "0")

    def test_login_2(self):
        u = JuqiAdmin(user="a1", password="a123")
        u.save()

        r = self.c.post(
            "/api/admin/login",
            {"user": "a1", "password": "a123"},
            content_type="application/json",
        )

        d = json.loads(r.content)
        print(self.c.session.items())
        self.assertEqual(d["code"], "0")

        token = self.c.session.get("login_token", "")
        self.assertEqual(len(token), 64)

        self.assertEqual(cache.get(token)["user"], "a1")

    def test_login_error_1(self):
        u = JuqiAdmin(user="a1", password="a123")
        u.save()

        r = self.c.post(
            "/api/admin/login",
            {"user": "a1", "password": "xxxxx"},
            content_type="application/json",
        )

        d = json.loads(r.content)
        print(self.c.session.items())

        self.assertEqual(d["code"], RightErr.code)

        token = self.c.session.get("login_token", "")
        self.assertEqual(len(token), 0)

    def test_logout(self):
        u = JuqiAdmin(user="a1", password="a123")
        u.save()

        u_s = JuqiAdminSerializer(u)

        # login
        r = self.c.post(
            "/api/admin/login",
            u_s.data,
            content_type="application/json",
        )

        d = json.loads(r.content)
        print(self.c.session.items())
        self.assertEqual(d["code"], "0")

        # logout
        r = self.c.post(
            "/api/admin/logout",
            content_type="application/json",
        )
        d = json.loads(r.content)
        print(f"logout: {d}")
        self.assertEqual(d["code"], "0")

        # logout again
        r = self.c.post(
            "/api/admin/logout",
            content_type="application/json",
        )
        d = json.loads(r.content)
        print(f"logout: {d}")
        self.assertEqual(d["code"], RightErr.code)

    # python manage.py test juqiadmin.tests.JuqiAdminTest.test_weight_random
    def test_weight_random(self):
        m = {
            "b": 9,
            "a": 1,
            "c": 90,
        }
        count = {}

        for i in range(1, 100000):
            r = weight_random(m)
            if not count.get(r, None):
                count[r] = 0
            count[r] += 1
        print(count)


# 封装管理员登录操作
def admin_login(c: Client):
    c.post(
        "/api/admin/login",
        {"user": "admin", "password": "admin123"},
        content_type="application/json",
    )


# 封装管理员登出操作
def admin_logout(c: Client):
    c.post(
        "/api/admin/logout",
        content_type="application/json",
    )


def gen_user():
    for i in range(10):
        Users.objects.create(
            openid="12121212121212121211212" + str(i),
            nickname="admin_" + str(i),
            realname="cc" + str(i),
            telephone="11111111111" + str(i),
            need_help=True,
            stored_money=randint(1000, 10000),
            score=randint(1000, 10000),
            hunjing=randint(10000, 1000000000),
        )

    return Users.objects.create(
        openid="12121212121212121211212",
        nickname="admin_a",
        realname="cc",
        telephone="11111111111",
        need_help=True,
        is_real=True,
        stored_money=int(1e8),
        score=int(1e8),
        hunjing=int(1e8),
    )


# def create_wuxianshang(wx_c, admin_c, user):
#     # 创建 boss 赏商品
#     goods = [
#         {
#             "name": "wxs_good_1",
#             "display_url": "img",
#             "price": 10e2,
#             "game_type": "无限赏",
#             "ip_family": "一拳超人",
#         },
#         {
#             "name": "wxs_good_2",
#             "display_url": "img",
#             "price": 100e2,
#             "game_type": "无限赏",
#             "ip_family": "一拳超人",
#         },
#         {
#             "name": "wxs_good_3",
#             "display_url": "img",
#             "price": 1000e2,
#             "game_type": "无限赏",
#             "ip_family": "一拳超人",
#         },
#         {
#             "name": "global_boss_good_1",
#             "display_url": "img",
#             "price": 10e2,
#             "game_type": "boss赏",
#             "ip_family": "一拳超人",
#         },
#         {
#             "name": "global_boss_good_2",
#             "display_url": "img",
#             "price": 20e2,
#             "game_type": "boss赏",
#             "ip_family": "一拳超人",
#         },
#         {
#             "name": "global_boss_good_3",
#             "display_url": "img",
#             "price": 30e2,
#             "game_type": "boss赏",
#             "ip_family": "一拳超人",
#         },
#         {
#             "name": "each_boss_good_1",
#             "display_url": "img",
#             "price": 1e2,
#             "game_type": "boss赏",
#             "ip_family": "一拳超人",
#         },
#     ]
#     good_name_map = {}
#     wxs_goods = []
#     boss_goods = []
#     for good in goods:
#         r = JuqiGoodTest.create_good(client=admin_c, good_info=good)
#         d = json.loads(r.content)
#         good_name_map[good["name"]] = d
#         if d["game_type"] == "无限赏":
#             wxs_goods.append(
#                 {"good_uuid": d["uuid"], "good_weight": 1, "good_rarity": "传说款"}
#             )
#         elif d["game_type"] == "boss赏":
#             is_global = int(str(d["name"]).startswith("global_"))
#             boss_goods.append(
#                 {
#                     "good_uuid": d["uuid"],
#                     "is_global": is_global,
#                     "good_rarity": "传说款",
#                     "count": 10,
#                 }
#             )

#     game = {
#         "name": "wxs_enable_boss",
#         "display_url": "http://",
#         "goods": wxs_goods,
#         "extend_type_boss": True,
#         "state": 1,
#         "extend_boss": {
#             "name": "boss赏1",
#             "ticket_weight": 1,
#             "draw_num": 100,
#             "display_url": "img",
#             "goods": boss_goods,
#         },
#     }

#     # 创建 无限赏 盒子
#     r = admin_c.post(
#         "/api/wuxianshang/game",
#         game,
#         content_type="application/json",
#     )
#     _game = json.loads(r.content)
#     _extend_boss = _game["extend_boss"]
#     _ticket_uuid = _extend_boss["ticket_uuid"]
#     _user = user
#     with patch("wuxianshang.views.wxs_raffle") as _wxs_raffle:
#         raffle_count = 101
#         _wxs_raffle.return_value = {_ticket_uuid: raffle_count}
#         params = {
#             "raffle_count": raffle_count,
#             "pay_type": "stored_money",
#             "game_uuid": _game["uuid"],
#         }
#         r = wx_c.post(
#             "/api/wuxianshang/raffle",
#             params,
#             content_type="application/json",
#         )
#         raffle_res = json.loads(r.content)

#         up = get_detail_UserPackage(_user)

#         all_sum = calculate_UserPackage_sum_price(_user.uuid)
#         current_date_sum = calculate_UserPackage_sum_price_by_date(
#             _user.uuid, datetime.datetime.now()
#         )


def gen_finance_data():
    users = Users.objects.filter(deleted=False)
    game_types = [
        GameType.wuxianshang,
        GameType.wuxianshang_boss,
        GameType.quanjushang,
        GameType.yifanshang,
    ]
    create_orders()
    for user in users:
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        finance.all_admin_recharge += randint(1000, 100000)
        finance.all_recharge += randint(100, 10000)
        finance.all_withdraw += randint(100, 100000)
        finance.save()
        game = QuanjushangGame.objects.filter(deleted=False).first()
        for game_type in game_types:
            finance = get_wxuser_finance(game_type, user.uuid, game.uuid)
            finance_game = get_game_finance(gameType=game_type)
            _all_raffle_income = randint(10000, 1000000)
            _all_raffle_cost = randint(10, 10000)
            finance.all_raffle_income += _all_raffle_income
            finance.all_raffle_cost += _all_raffle_cost
            finance_game.all_raffle_income += _all_raffle_income
            finance_game.all_raffle_cost += _all_raffle_cost
            update_finnce_profit(finance)
            update_finnce_profit(finance_game)
            finance.save()
            finance_game.save()


def create_goods():
    for i in range(5):
        JuqiGood(
            name="小汽车" + str(randint(100, 10000)),
            display_url="123" + str(randint(100, 10000)),
            price=50 + randint(100, 1000),
            recovery_price=10 + randint(0, 100),
            game_type="全局赏",
            ip_family="123" + str(randint(100, 10000)),
            # 商品详细介绍
            detail="123" + str(randint(100, 10000)),
        ).save()


def create_orders():
    create_goods()
    users = Users.objects.filter(deleted=False).all()
    goods = JuqiGood.objects.filter(deleted=False).all()

    game = QuanjushangGame.objects.create(
        name="test池子", cover_url="123", user_limit=1, price=10, game_num=50
    )
    son_game_ = []
    for v in range(1, 5 + 1):
        i = {"game_uuid": game.uuid, "user_limit": 1, "price": 1000, "box_num": v}
        son_game_.append(QuanjushangSonGame(**i))
    son_games = QuanjushangSonGame.objects.bulk_create(son_game_)

    for user in users:
        for son_game in son_games:
            user_order = UserOrder.objects.create(
                user_uuid=user.uuid,
                game_type=GameType.quanjushang.value,
                game_uuid=game.uuid,
                game_name=game.name,
                son_uuid=son_game.uuid,
                box_num=son_game.box_num,
                num=game.game_num,
                money=game.price,
                price=game.price,
                hunjing=0,
                score=0,
                weixin=0,
                orderid=order_uuid("CS_"),
            )
            for good in goods:
                for i in range(randint(1, 5)):
                    UserPackageGoods(
                        order_uuid=user_order.uuid,
                        good_uuid=good.uuid,
                        user_uuid=user.uuid,
                        good_level_title="A赏品",
                        game_type=GameType.quanjushang.value,
                        game_uuid=game.uuid,
                        game_son_uuid=son_game.uuid,
                        game_box_num=son_game.box_num,
                        order_num=i,
                    ).save()
                    finance = get_wxuser_finance(
                        GameType.quanjushang, user.uuid, game.uuid
                    )
                    finance_game = get_game_finance(gameType=GameType.quanjushang)
                    _all_raffle_income = randint(10000, 1000000)
                    _all_raffle_cost = randint(10, 10000)
                    finance.all_raffle_income += _all_raffle_income
                    finance.all_raffle_cost += _all_raffle_cost
                    finance_game.all_raffle_income += _all_raffle_income
                    finance_game.all_raffle_cost += _all_raffle_cost
                    update_finnce_profit(finance)
                    update_finnce_profit(finance_game)
                    finance.save()
                    finance_game.save()


class JuqiUserTest(TestCase):
    def setUp(self):
        self.admin_c = Client()
        self.user = gen_user()
        self.wx_c = Client(HTTP_X_WX_OPENID=self.user.openid)
        self.user_s = UserSerializer(self.user)
        self.user_r_s = UserResultSerializer(self.user)

    def test_get_user(self):
        admin_login(self.admin_c)  # 登录管理员

        # 测试登录状态下get方法无参
        res = self.admin_c.get("/api/admin/user")
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        data: dict = json.loads(res.content)

        _count = data.get("sum_count")
        self.assertIsNotNone(_count)

        _list: list = data.get("list")
        self.assertIsNotNone(_list)

        _min = min(20, _count)
        self.assertEqual(len(_list), _min)

        # 测试登录状态下get方法 分页参数
        page = 1
        page_size = 4

        res = self.admin_c.get(
            "/api/admin/user", {"page": page, "page_size": page_size}
        )
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        data: dict = json.loads(res.content)

        _count = data.get("sum_count")
        pprint(data)
        self.assertIsNotNone(_count)

        _list: list = data.get("list")
        self.assertIsNotNone(_list)

        _min = min(page_size, _count)
        self.assertEqual(len(_list), _min)

        # 测试登录状态下get方法 过滤参数

        filters = [
            "uuid",
            "nickname",
            "telephone",
            "is_real",
            "createdAt_start",
            "createdAt_end",
        ]

        for f in filters:
            key = f
            if key.endswith("_start") or key.endswith("_end"):
                if key.endswith("_end"):
                    self.user.createdAt += datetime.timedelta(seconds=1)
                    self.user_s = UserSerializer(self.user)
                key = key.replace("_start", "").replace("_end", "")

            res = self.admin_c.get("/api/admin/user", {f: self.user_s.data.get(key)})
            self.assertEqual(res.status_code, status.HTTP_200_OK)
            data: dict = json.loads(res.content)
            _count = data.get("sum_count")
            self.assertIsNotNone(_count)
            self.assertGreaterEqual(_count, 1)
            _list: list = data.get("list")
            self.assertIsNotNone(_list)

            # self.assertEqual(self.user_r_s.data, _list[_count - 1])

        admin_logout(self.admin_c)  # 登出管理员

        res = self.admin_c.get("/api/admin/user")
        self.assertError(res, -10002, "error right")

        # 还原
        self.user = (
            Users.objects.filter(deleted=False).filter(uuid=self.user.uuid).first()
        )
        self.user_s = UserSerializer(self.user)

    def test_del_user(self):
        admin_login(self.admin_c)  # 登录管理员

        res = self.admin_c.get("/api/admin/user")
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        data: dict = json.loads(res.content)

        _count = data.get("sum_count")

        _list: list = data.get("list")
        uuid = _list[0].get("uuid")

        # 测试管理员删除用户
        res = self.admin_c.delete("/api/admin/user?uuid=" + uuid)
        self.assertOk(res)

        admin_logout(self.admin_c)  # 登出管理员

        # 测试未认证删除用户
        res = self.admin_c.delete("/api/admin/user?uuid=" + uuid)
        self.assertError(res, -10002, "error right")

    def test_get_user_details(self):
        admin_login(self.admin_c)
        create_orders()
        # 正确性测试
        res = self.admin_c.get(
            "/api/admin/user_details", {"uuid": self.user_s.data.get("uuid")}
        )
        data = self.assertOk(res)
        _data = data.get("data")
        pprint(_data)
        self.assertIsNotNone(_data)
        self.assertEqual(_data, self.user_r_s.data)

        # 错误uuid格式
        res = self.admin_c.get(
            "/api/admin/user_details", {"uuid": "22ea1bc9-ac9e-42d9-83d1-50d91335"}
        )

        self.assertError(res, "invalid", "“%(value)s”不是一个有效的UUID")

        # 不存在的uuid
        res = self.admin_c.get(
            "/api/admin/user_details", {"uuid": "22ea1bc9-ac9e-42d9-83d1-50d913353b"}
        )
        self.assertError(res, "invalid", "“%(value)s”不是一个有效的UUID")

        admin_logout(self.admin_c)

        # 未登录状态下测试
        res = self.admin_c.get(
            "/api/admin/user_details", {"uuid": self.user_s.data.get("uuid")}
        )
        self.assertError(res, -10002, "error right")

    def test_user_action_stored_money_recharge(self):
        """
        测试管理员余额充值
        """
        stored_money = randint(100, 1000)

        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_stored_money = user.stored_money

        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        _old_all_admin_recharge = finance.all_admin_recharge

        _old_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_old_stored_money + stored_money)
            .count()
        )

        admin = JuqiAdmin.objects.filter(deleted=False).get(user="admin")
        self.assertIsNotNone(admin)

        _old_order_count = (
            UserRechargeOrder.objects.filter(deleted=False)
            .filter(openid=user.openid)
            .filter(total_fee=stored_money)
            .filter(state=OrderState.success.value)
            .filter(recharge_type=UserRechargeType.admin)
            .filter(admin_uuid=admin.uuid)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/recharge",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": stored_money},
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_stored_money = user.stored_money
        self.assertEqual(_new_stored_money, _old_stored_money + stored_money)

        # 测试统计表是否变动
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        _new_all_admin_recharge = finance.all_admin_recharge
        self.assertEqual(
            _new_all_admin_recharge, _old_all_admin_recharge + stored_money
        )

        # 测试记录表是否记录
        _new_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_new_stored_money)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count + 1)

        # 测试订单表是否记录
        _new_order_count = (
            UserRechargeOrder.objects.filter(deleted=False)
            .filter(openid=user.openid)
            .filter(total_fee=stored_money)
            .filter(state=OrderState.success.value)
            .filter(recharge_type=UserRechargeType.admin)
            .filter(admin_uuid=admin.uuid)
            .count()
        )
        self.assertEqual(_new_order_count, _old_order_count + 1)

        # 错误测试
        _old_stored_money = user.stored_money
        _old_all_admin_recharge = _new_all_admin_recharge
        _old_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_old_stored_money + stored_money)
            .count()
        )

        _old_order_count = (
            UserRechargeOrder.objects.filter(deleted=False)
            .filter(openid=user.openid)
            .filter(total_fee=stored_money)
            .filter(state=OrderState.success.value)
            .filter(recharge_type=UserRechargeType.admin)
            .filter(admin_uuid=admin.uuid)
            .count()
        )

        # 测试错误传参
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/recharge",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": -stored_money},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/storedmoney/recharge",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/storedmoney/recharge",
            {"user_uuid": "112233445566", "stored_money": stored_money},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/storedmoney/recharge",
            {
                "user_uuid": "67770ebd94f749a39056ad9cd460d442",
                "stored_money": stored_money,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/recharge",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": stored_money},
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.stored_money, _old_stored_money)

        # 测试金额表没有发生变化
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        self.assertEqual(finance.all_admin_recharge, _old_all_admin_recharge)

        # 测试统计表没有发生变化
        _new_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_new_stored_money)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count)

        # 测试订单表没有发生变化
        _new_order_count = (
            UserRechargeOrder.objects.filter(deleted=False)
            .filter(openid=user.openid)
            .filter(total_fee=stored_money)
            .filter(state=OrderState.success.value)
            .filter(recharge_type=UserRechargeType.admin)
            .filter(admin_uuid=admin.uuid)
            .count()
        )
        self.assertEqual(_new_order_count, _old_order_count)

    def test_user_action_stored_money_refund(self):
        """
        测试管理员余额退款
        """

        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_stored_money = user.stored_money

        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        if finance.all_admin_recharge == 0:
            finance.all_admin_recharge = 1000
            finance.save()
            finance = get_wxuser_recharge_withdraw_finance(user.uuid)
            self.assertIsNotNone(finance)

        _old_all_admin_recharge = finance.all_admin_recharge

        stored_money = randint(1, _old_all_admin_recharge)  # 防止随机越界

        _old_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_old_stored_money - stored_money)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": stored_money},
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_stored_money = user.stored_money
        self.assertEqual(_new_stored_money, _old_stored_money - stored_money)

        # 测试统计表是否变动
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        _new_all_admin_recharge = finance.all_admin_recharge
        self.assertEqual(
            _new_all_admin_recharge, _old_all_admin_recharge - stored_money
        )

        # 测试记录表是否记录
        _new_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=-stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_new_stored_money)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count + 1)

        # 错误测试
        _old_stored_money = user.stored_money
        _old_all_admin_recharge = _new_all_admin_recharge
        _old_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=-stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_old_stored_money - stored_money)
            .count()
        )

        # 测试错误传参
        # 传入负数
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": -stored_money},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 传入零
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 退款数超过了当前用户金额
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "stored_money": user.stored_money + 1,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {"user_uuid": "112233445566", "stored_money": stored_money},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {
                "user_uuid": "67770ebd94f749a39056ad9cd460d442",
                "stored_money": stored_money,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/storedmoney/refund",
            {"user_uuid": self.user_s.data.get("uuid"), "stored_money": stored_money},
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.stored_money, _old_stored_money)

        # 测试金额表没有发生变化
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        self.assertEqual(finance.all_admin_recharge, _old_all_admin_recharge)

        # 测试统计表没有发生变化
        _new_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=-stored_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_new_stored_money)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count)

    def test_user_action_hunjing_recharge(self):
        """
        测试管理员魂晶充值
        """

        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_hunjing = user.hunjing

        hunjing = randint(1, _old_hunjing)

        _old_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_old_hunjing - hunjing)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/hunjing/recharge",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": hunjing,
            },
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_hunjing = user.hunjing
        self.assertEqual(_new_hunjing, _old_hunjing + hunjing)

        (withdraw_money, mod) = divmod(hunjing, Constants.HUNJING_WITHDRAW_RATIO)
        self.assertEqual(mod, 0)

        # 测试记录表是否记录
        _new_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count + 1)

        # 错误测试
        _old_hunjing = _new_hunjing
        _old_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing + hunjing)
            .count()
        )

        # 测试错误传参
        # 传入负数
        res = self.admin_c.put(
            "/api/admin/user/hunjing/recharge",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": -hunjing,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 传入零
        res = self.admin_c.put(
            "/api/admin/user/hunjing/recharge",
            {"user_uuid": self.user_s.data.get("uuid"), "hunjing": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/hunjing/recharge",
            {"user_uuid": "112233445566", "hunjing": hunjing},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/hunjing/recharge",
            {"user_uuid": "67770ebd94f749a39056ad9cd460d442", "hunjing": hunjing},
            content_type="application/json",
        )

        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/hunjing/recharge",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": hunjing,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.hunjing, _old_hunjing)

        # 测试统计表没有发生变化
        _new_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count)

    def test_user_action_hunjing_withdraw(self):
        """
        测试管理员余额退款
        """

        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_hunjing = user.hunjing

        if _old_hunjing <= 1000:
            user.hunjing = 100000
            user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
            self.assertIsNotNone(user)
            _old_hunjing = user.hunjing

        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        _old_all_withdraw = finance.all_withdraw

        hunjing = (
            randint(1, int(_old_hunjing / Constants.HUNJING_WITHDRAW_RATIO))
            * Constants.HUNJING_WITHDRAW_RATIO
        )  # 防止随机越界

        (withdraw_money, mod) = divmod(hunjing, Constants.HUNJING_WITHDRAW_RATIO)

        _old_stored_money = user.stored_money
        self.assertEqual(mod, 0)

        admin = JuqiAdmin.objects.filter(deleted=False).get(user="admin")
        self.assertIsNotNone(admin)

        _old_hunjing_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_old_hunjing - hunjing)
            .count()
        )

        _old_stored_money_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=withdraw_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_old_stored_money + withdraw_money)
            .count()
        )

        _old_user_withdraw_count = (
            UserWithdraw.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(admin_uuid=admin.uuid)
            .filter(withdraw_money=withdraw_money)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_old_hunjing - hunjing)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": hunjing,
            },
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_hunjing = user.hunjing
        self.assertEqual(_new_hunjing, _old_hunjing - hunjing)

        _new_stored_money = user.stored_money
        self.assertEqual(_new_stored_money, _old_stored_money + withdraw_money)

        # 测试统计表是否变动
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        _new_all_withdraw = finance.all_withdraw
        self.assertEqual(_new_all_withdraw, _old_all_withdraw + withdraw_money)

        # 测试记录表是否记录
        _new_hunjing_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )
        self.assertEqual(_new_hunjing_record_count, _old_hunjing_record_count + 1)

        _new_stored_money_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=withdraw_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_new_stored_money)
            .count()
        )
        self.assertEqual(
            _new_stored_money_record_count, _old_stored_money_record_count + 1
        )

        _new_user_withdraw_count = (
            UserWithdraw.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(admin_uuid=admin.uuid)
            .filter(withdraw_money=withdraw_money)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )

        self.assertEqual(_new_user_withdraw_count, _old_user_withdraw_count + 1)

        # 错误测试
        _old_hunjing = _new_hunjing
        _old_stored_money = _old_stored_money
        _old_all_withdraw = _new_all_withdraw

        _old_hunjing_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_old_hunjing - hunjing)
            .count()
        )

        _old_stored_money_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=withdraw_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_old_stored_money + withdraw_money)
            .count()
        )

        _old_user_withdraw_count = (
            UserWithdraw.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(admin_uuid=admin.uuid)
            .filter(withdraw_money=withdraw_money)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_old_hunjing - hunjing)
            .count()
        )

        # 测试错误传参
        # 传入负数
        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": -hunjing,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 传入零
        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {"user_uuid": self.user_s.data.get("uuid"), "hunjing": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 退款数超过了当前用户金额
        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": user.hunjing + 1,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {"user_uuid": "112233445566", "hunjing": hunjing},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {"user_uuid": "67770ebd94f749a39056ad9cd460d442", "hunjing": hunjing},
            content_type="application/json",
        )

        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/hunjing/withdraw",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": hunjing,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.hunjing, _old_hunjing)

        # 测试金额表没有发生变化
        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        self.assertIsNotNone(finance)

        self.assertEqual(finance.all_withdraw, _old_all_withdraw)

        # 测试统计表没有发生变化
        _new_hunjing_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )

        self.assertEqual(_new_hunjing_record_count, _old_hunjing_record_count)

        _new_stored_money_record_count = (
            UserStoredMoneyRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(stored_money=withdraw_money)
            .filter(old_stored_money=_old_stored_money)
            .filter(new_stored_money=_new_stored_money)
            .count()
        )
        self.assertEqual(_new_stored_money_record_count, _old_stored_money_record_count)

        _new_user_withdraw_count = (
            UserWithdraw.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(admin_uuid=admin.uuid)
            .filter(withdraw_money=withdraw_money)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )

        self.assertEqual(_new_user_withdraw_count, _old_user_withdraw_count)

    def test_user_action_hunjing_deduction(self):
        """
        测试管理员魂晶扣除
        """

        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_hunjing = user.hunjing

        if _old_hunjing <= 1000:
            user.hunjing = 100000
            user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
            self.assertIsNotNone(user)

            _old_hunjing = user.hunjing

        hunjing = randint(1, int(_old_hunjing / 1000)) * 1000  # 防止随机越界

        _old_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_old_hunjing - hunjing)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": hunjing,
            },
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_hunjing = user.hunjing
        self.assertEqual(_new_hunjing, _old_hunjing - hunjing)

        # 测试统计表是否变动
        (withdraw_money, mod) = divmod(hunjing, Constants.HUNJING_WITHDRAW_RATIO)
        self.assertEqual(mod, 0)

        # 测试记录表是否记录
        _new_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count + 1)

        # 错误测试
        _old_hunjing = _new_hunjing
        _old_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing - hunjing)
            .count()
        )

        # 测试错误传参
        # 传入负数
        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": -hunjing,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 传入零
        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {"user_uuid": self.user_s.data.get("uuid"), "hunjing": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 退款数超过了当前用户金额
        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": user.hunjing + 1,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {"user_uuid": "112233445566", "hunjing": hunjing},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {"user_uuid": "67770ebd94f749a39056ad9cd460d442", "hunjing": hunjing},
            content_type="application/json",
        )

        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/hunjing/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "hunjing": hunjing,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.hunjing, _old_hunjing)

        # 测试统计表没有发生变化
        _new_record_count = (
            UserHunJingRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(hunjing=-hunjing)
            .filter(old_hunjing=_old_hunjing)
            .filter(new_hunjing=_new_hunjing)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count)

    def test_user_action_score_recharge(self):
        """
        测试管理员积分充值
        """
        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_score = user.score

        score = randint(1, _old_score)  # 防止随机越界

        _old_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=score)
            .filter(old_score=_old_score)
            .filter(new_score=_old_score - score)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/score/recharge",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": score,
            },
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_score = user.score
        self.assertEqual(_new_score, _old_score + score)

        # 测试记录表是否记录
        _new_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=score)
            .filter(old_score=_old_score)
            .filter(new_score=_new_score)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count + 1)

        # 错误测试
        _old_score = _new_score
        _old_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=score)
            .filter(old_score=_old_score)
            .filter(new_score=_new_score + score)
            .count()
        )

        # 测试错误传参
        # 传入负数
        res = self.admin_c.put(
            "/api/admin/user/score/recharge",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": -score,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 传入零
        res = self.admin_c.put(
            "/api/admin/user/score/recharge",
            {"user_uuid": self.user_s.data.get("uuid"), "score": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/score/recharge",
            {"user_uuid": "112233445566", "score": score},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/score/recharge",
            {"user_uuid": "67770ebd94f749a39056ad9cd460d442", "score": score},
            content_type="application/json",
        )

        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/score/recharge",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": score,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.score, _old_score)

        # 测试统计表没有发生变化
        _new_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=score)
            .filter(old_score=_old_score)
            .filter(new_score=_new_score)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count)

    def test_user_action_score_deduction(self):
        """
        测试管理员扣除
        """

        admin_login(self.admin_c)
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _old_score = user.score

        score = randint(1, _old_score)  # 防止随机越界

        if _old_score <= 1000:
            user.score = 100000
            user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
            self.assertIsNotNone(user)

            _old_score = user.score

        _old_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=-score)
            .filter(old_score=_old_score)
            .filter(new_score=_old_score - score)
            .count()
        )

        # 正确性测试
        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": score,
            },
            content_type="application/json",
        )
        self.assertOk(res)

        # 测试用户表是否变动
        user = Users.objects.filter(deleted=False).get(uuid=self.user.uuid)
        self.assertIsNotNone(user)

        _new_score = user.score
        self.assertEqual(_new_score, _old_score - score)

        # 测试记录表是否记录
        _new_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=-score)
            .filter(old_score=_old_score)
            .filter(new_score=_new_score)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count + 1)

        # 错误测试
        _old_score = _new_score
        _old_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=-score)
            .filter(old_score=_old_score)
            .filter(new_score=_new_score - score)
            .count()
        )

        # 测试错误传参
        # 传入负数
        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": -score,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 传入零
        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {"user_uuid": self.user_s.data.get("uuid"), "score": 0},
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 退款数超过了当前用户金额
        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": user.score + 1,
            },
            content_type="application/json",
        )
        self.assertError(res, ValueErr.code, ValueErr.msg)

        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {"user_uuid": "112233445566", "score": score},
            content_type="application/json",
        )
        self.assertError(
            res,
            "invalid",
            "“%(value)s”不是一个有效的UUID",
        )

        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {"user_uuid": "67770ebd94f749a39056ad9cd460d442", "score": score},
            content_type="application/json",
        )

        self.assertError(res, ValueErr.code, ValueErr.msg)

        # 测试未登录状态下请求
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/score/deduction",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "score": score,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

        user = Users.objects.get(uuid=self.user.uuid)
        self.assertEqual(user.score, _old_score)

        # 测试统计表没有发生变化
        _new_record_count = (
            UserScoreRecord.objects.filter(deleted=False)
            .filter(user_uuid=user.uuid)
            .filter(score=-score)
            .filter(old_score=_old_score)
            .filter(new_score=_new_score)
            .count()
        )
        self.assertEqual(_new_record_count, _old_record_count)

    def test_user_finance(self):
        user_list = generate_db_user_list(10)
        game_types = [
            GameType.wuxianshang,
            GameType.quanjushang,
            GameType.wuxianshang_boss,
        ]
        game = QuanjushangGame.objects.create(
            name="test池子", cover_url="123", user_limit=1, price=10, game_num=50
        )

        for user in user_list:
            for _game_type in game_types:
                get_wxuser_recharge_withdraw_finance(user_uuid=user.uuid)
                get_wxuser_finance(
                    gameType=_game_type, user_uuid=user.uuid, game_uuid=game.uuid
                )

        _start = datetime.datetime(2020, 1, 1)

        quanjushang_types = [
            GameType.quanjushang.value,
            GameType.wuxianshang_boss.value,
        ]
        wuxianshang_types = [GameType.wuxianshang.value]

        user = user_list[0]

        _user_finance_query = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(user_uuid=user.uuid)
            .filter(createdAt__gte=_start)
        )

        ps = get_detail_UserPackage(user)

        print(ps)

        ff = (
            _user_finance_query.all()
            .values("user_uuid")
            .annotate(
                user_cost=Value(
                    user.stored_money
                    + user.hunjing
                    + int(user.score / Constants.SCORE_WITHDRAW_RATIO)
                ),
                wx_recharge=Sum("all_recharge"),
                admin_recharge=Sum("all_admin_recharge"),
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
                whole_withdraw=Sum("all_withdraw"),
                whole_shipper_cost=Value(0),  # todo 发货价值 订单系统完善后补充
                wuxianshang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=wuxianshang_types),
                ),
                wuxianshang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=wuxianshang_types),
                ),
                quanjushang_raffle_income=Sum(
                    "all_raffle_income", filter=Q(game_type__in=quanjushang_types)
                ),
                quanjushang_raffle_cost=Sum(
                    "all_raffle_cost", filter=Q(game_type__in=quanjushang_types)
                ),
                whole_raffle_income=Sum("all_raffle_income"),
                whole_raffle_cost=Sum("all_raffle_cost"),
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
            .values(
                "user_cost",
                "wx_recharge",
                "admin_recharge",
                "whole_recharge",
                "whole_withdraw",
                "whole_shipper_cost",
                "wuxianshang_raffle_income",
                "wuxianshang_raffle_cost",
                "quanjushang_raffle_income",
                "quanjushang_raffle_cost",
                "whole_raffle_income",
                "whole_raffle_cost",
                "whole_raffle_profit",
            )
        )
        print(ff[0])

        fs = (
            _user_finance_query.all()
            .annotate(date=TruncDay("createdAt"))
            .values("date")
            .annotate(
                user_id=Value(user.id),
                user_name=Value(user.nickname),
                user_head_url=Value(user.head_url),
                whole_shipper_cost=Value(0),  # todo 发货价值 订单系统完善后补充
                whole_packages_cost=Value(0),
                wx_recharge=Sum("all_recharge"),
                admin_recharge=Sum("all_admin_recharge"),
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
                whole_withdraw=Sum("all_withdraw"),
                wuxianshang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=wuxianshang_types),
                ),
                wuxianshang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=wuxianshang_types),
                ),
                quanjushang_raffle_income=Sum(
                    "all_raffle_income", filter=Q(game_type__in=quanjushang_types)
                ),
                quanjushang_raffle_cost=Sum(
                    "all_raffle_cost", filter=Q(game_type__in=quanjushang_types)
                ),
                whole_raffle_income=Sum("all_raffle_income"),
                whole_raffle_cost=Sum("all_raffle_cost"),
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
            .values(
                "date",
                "user_id",
                "user_name",
                "user_head_url",
                "whole_shipper_cost",
                "whole_packages_cost",
                "wx_recharge",
                "admin_recharge",
                "whole_recharge",
                "whole_withdraw",
                "wuxianshang_raffle_income",
                "wuxianshang_raffle_cost",
                "quanjushang_raffle_income",
                "quanjushang_raffle_cost",
                "whole_raffle_income",
                "whole_raffle_cost",
                "whole_raffle_profit",
            )
            .order_by("-date")
        )

        for f in fs:
            # print(FinanceSerializer(f).data)
            date = f.get("date")
            f["whole_packages_cost"] = calculate_UserPackage_sum_price_by_date(
                user_uuid=user.uuid, sum_date=date
            )

        for f in fs:
            print(f)

    def test_user_profit(self):
        """
        用户盈亏

        """
        admin_login(self.admin_c)
        # create_wuxianshang(self.wx_c, self.admin_c, self.user)
        gen_finance_data()
        res = self.admin_c.get(
            "/api/admin/user/profit",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "date_start": datetime.datetime.now().strftime("%Y-%m-%d"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_packages(self):
        """用户赏柜详情"""
        admin_login(self.admin_c)
        create_orders()
        res = self.admin_c.get(
            "/api/admin/user/packages",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "date_start": "2023-03-12",
                "date_end": "2023-03-13",
                "page": 1,
                "page_size": 50,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_rank_recharge(self):
        """
        充值排行榜
        """
        admin_login(self.admin_c)
        gen_finance_data()
        res = self.admin_c.get(
            "/api/admin/user/rank/recharge",
            {
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        # 测试排除uid是否生效
        settings = get_web_settings(locked=True)
        # settings.statistical_exclude_user_id = (
        #     str(self.user_s.data.get("id")) + ""
        # )  # 修改网站配置
        pprint(WebSettingsSerializer(settings).data)
        settings.save()
        pprint(get_web_settings_statistical_exclude_user_uid_list())
        pprint(get_web_settings_statistical_exclude_user_uuid_list())
        fin = get_wxuser_recharge_withdraw_finance(self.user_s.data.get("uuid"))

        fin_data = FinanceSerializer(fin).data
        pprint(fin_data)

        fin = get_wxuser_finance(
            GameType.quanjushang,
            self.user.uuid,
            QuanjushangGame.objects.all().first().uuid,
        )
        fin_data = FinanceSerializer(fin).data

        pprint(fin_data)

        res = self.admin_c.get(
            "/api/admin/user/rank/recharge",
            {
                "date": datetime.datetime.now().strftime("%Y-%m-%d"),
                "uid": self.user_s.data.get("id"),
                "page": 1,
                "page_size": 5,
            },
        )
        self.assertError(res, RightErr.code, RightErr.msg)
        settings.statistical_exclude_user_id = ""  # 手动还原修改
        settings.save()

    def test_user_rank_consumption(self):
        """
        消费排行榜
        """
        admin_login(self.admin_c)
        gen_finance_data()
        res = self.admin_c.get(
            "/api/admin/user/rank/consumption",
            {
                "date": datetime.datetime.now().strftime("%Y-%m-%d"),
                "uid": 1000,
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        # 测试排除uid是否生效
        settings = get_web_settings(locked=True)
        settings.statistical_exclude_user_id = (
            str(self.user_s.data.get("id")) + ",  "
        )  # 修改网站配置
        pprint(WebSettingsSerializer(settings).data)
        settings.save()
        res = self.admin_c.get(
            "/api/admin/user/rank/consumption",
            {
                "date": datetime.datetime.now().strftime("%Y-%m-%d"),
                "uid": self.user_s.data.get("id"),
                "page": 1,
                "page_size": 5,
            },
        )
        self.assertError(res, RightErr.code, RightErr.msg)
        settings.statistical_exclude_user_id = ""  # 手动还原修改
        settings.save()

    def test_user_rank_profit(self):
        """
        盈利排行榜
        """
        admin_login(self.admin_c)
        gen_finance_data()
        res = self.admin_c.get(
            "/api/admin/user/rank/profit",
            {
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        # 测试排除uid是否生效
        settings = get_web_settings(locked=True)
        settings.statistical_exclude_user_id = (
            str(self.user_s.data.get("id")) + ",  "
        )  # 修改网站配置
        pprint(WebSettingsSerializer(settings).data)
        settings.save()
        res = self.admin_c.get(
            "/api/admin/user/rank/profit",
            {
                "date": datetime.datetime.now().strftime("%Y-%m-%d"),
                "uid": self.user_s.data.get("id"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)
        settings.statistical_exclude_user_id = ""  # 手动还原修改
        settings.save()

    def test_user_finance_day(self):
        """
        测试财务明细 日账单
        """
        admin_login(self.admin_c)
        gen_finance_data()
        res = self.admin_c.get(
            "/api/admin/finance/day",
            {
                "date_start": datetime.datetime.now().strftime("%Y-%m-%d"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        # 测试排除uid是否生效
        settings = get_web_settings(locked=True)
        settings.statistical_exclude_user_id = (
            str(self.user_s.data.get("id")) + ",  "
        )  # 修改网站配置
        pprint(WebSettingsSerializer(settings).data)
        settings.save()

        res = self.admin_c.get(
            "/api/admin/finance/day",
            {
                "date_start": datetime.datetime.now().strftime("%Y-%m-%d"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        settings.statistical_exclude_user_id = ""  # 手动还原修改
        settings.save()

    def test_user_finance_month(self):
        """
        测试财务明细 月账单
        """
        admin_login(self.admin_c)
        gen_finance_data()
        res = self.admin_c.get(
            "/api/admin/finance/month",
            {
                "date_start": datetime.datetime.now().strftime("%Y-%m"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        # 测试排除uid是否生效
        settings = get_web_settings(locked=True)
        settings.statistical_exclude_user_id = (
            str(self.user_s.data.get("id")) + ",  "
        )  # 修改网站配置
        pprint(WebSettingsSerializer(settings).data)
        settings.save()

        res = self.admin_c.get(
            "/api/admin/finance/day",
            {
                "date_start": datetime.datetime.now().strftime("%Y-%m-%d"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        settings.statistical_exclude_user_id = ""  # 手动还原修改
        settings.save()

    def test_user_up_daili(self):
        """
        测试更新代理状态
        """
        admin_login(self.admin_c)
        old_is_daili = self.user.is_daili
        res = self.admin_c.put(
            "/api/admin/user/daili",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "daili": not old_is_daili,
            },
            content_type="application/json",
        )
        self.assertOk(res)
        new_is_daili = (
            Users.objects.filter(deleted=False)
            .filter(uuid=self.user.uuid)
            .first()
            .is_daili
        )
        self.assertEqual(new_is_daili, not old_is_daili)
        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/daili",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "daili": not old_is_daili,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

    def test_user_up_disable(self):
        """
        测试禁用状态
        """
        admin_login(self.admin_c)
        old_is_disable = self.user.state.value is UserState.block.value
        res = self.admin_c.put(
            "/api/admin/user/disable",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "disable": not old_is_disable,
            },
            content_type="application/json",
        )
        self.assertOk(res)
        new_is_disable = (
            Users.objects.filter(deleted=False)
            .filter(uuid=self.user.uuid)
            .first()
            .state
            is UserState.block.value
        )
        self.assertEqual(new_is_disable, not old_is_disable)

        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/disable",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "disable": not old_is_disable,
            },
            content_type="application/json",
        )

        self.assertError(res, RightErr.code, RightErr.msg)

    def test_user_up_real(self):
        """
        测试实名认证
        """
        _real_name = "王富贵"
        _idcard_num = "150102199003073435"
        admin_login(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/real",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "real_name": _real_name,
                "idcard_num": _idcard_num,
            },
            content_type="application/json",
        )

        self.assertOk(res)

        user = Users.objects.filter(deleted=False).filter(uuid=self.user.uuid).first()

        self.assertEqual(user.realname, _real_name)
        self.assertEqual(user.idcard_num, _idcard_num)
        self.assertEqual(user.is_real, True)

        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/real",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "real_name": _real_name,
                "idcard_num": _idcard_num,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

    def test_user_up_inviter(self):
        """
        测试修改推荐人
        """

        _inviter_user = Users.objects.filter(deleted=False).all()[3]
        admin_login(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/inviter",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "inviter_name": _inviter_user.nickname,
            },
            content_type="application/json",
        )

        self.assertOk(res)

        user = Users.objects.filter(deleted=False).filter(uuid=self.user.uuid).first()

        self.assertEqual(user.inviter_uuid, _inviter_user.uuid)

        admin_logout(self.admin_c)
        res = self.admin_c.put(
            "/api/admin/user/inviter",
            {
                "user_uuid": self.user_s.data.get("uuid"),
                "inviter_name": _inviter_user.nickname,
            },
            content_type="application/json",
        )
        self.assertError(res, RightErr.code, RightErr.msg)

    def test_user_record_recharge(self):
        """
        测试用户充值记录
        """
        admin_login(self.admin_c)
        UserRechargeOrder(
            openid=self.user.openid,
            total_fee=randint(100, 10000),
            recharge_type=UserRechargeType.weixin,
            state=OrderState.success.value,
        ).save()
        for i in range(10):
            stored_money = randint(100, 10000)
            res = self.admin_c.put(
                "/api/admin/user/storedmoney/recharge",
                {
                    "user_uuid": self.user_s.data.get("uuid"),
                    "stored_money": stored_money,
                },
                content_type="application/json",
            )
            self.assertOk(res)

        res = self.admin_c.get(
            "/api/admin/user/record/recharge",
            {
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

        res = self.admin_c.get(
            "/api/admin/user/record/recharge",
            {
                "uid": self.user.id,
                "name": self.user.nickname,
                "date_end": datetime.datetime.now().strftime("%Y-%m-%d"),
                "type": UserRechargeType.weixin.value,
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_record_withdraw(self):
        """
        测试用户提现记录
        """
        admin_login(self.admin_c)
        for i in range(10):
            hunjing = randint(100, 10000)
            res = self.admin_c.put(
                "/api/admin/user/hunjing/withdraw",
                {
                    "user_uuid": self.user_s.data.get("uuid"),
                    "hunjing": hunjing,
                },
                content_type="application/json",
            )
            self.assertOk(res)

        res = self.admin_c.get(
            "/api/admin/user/record/withdraw",
            {
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        # pprint(_data)

        res = self.admin_c.get(
            "/api/admin/user/record/withdraw",
            {
                "uid": self.user.id,
                "name": self.user.nickname,
                "date_start": datetime.datetime.now().strftime("%Y-%m-%d"),
                "date_end": datetime.datetime.now().strftime("%Y-%m-%d"),
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        # pprint(_data)

        res = self.admin_c.get("/api/admin/home")
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_get_web_settings(self):
        admin_login(self.admin_c)
        res = self.admin_c.get("/api/admin/settings/web")
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_up_web_settings(self):
        admin_login(self.admin_c)

        _name = ""
        _freight_code = ""
        _goods_freight_money = randint(1000, 10000)
        _goods_less_count = randint(1, 100)
        _goods_recycle_less_money = randint(1000, 100000)
        _hidden_box_consume = randint(1000, 100000)
        _recharge_page_switch = False
        _statistical_exclude_user_id = ""
        res = self.admin_c.put(
            "/api/admin/settings/web",
            {
                "freight_code": _freight_code,
                "goods_freight_money": _goods_freight_money,
                "goods_less_count": _goods_less_count,
                "goods_recycle_less_money": _goods_recycle_less_money,
                "hidden_box_consume": _hidden_box_consume,
                "name": _name,
                "recharge_page_switch": _recharge_page_switch,
                "statistical_exclude_user_id": _statistical_exclude_user_id,
            },
            content_type="application/json",
        )
        _data = self.assertOk(res)
        _data = _data.get("data")
        pprint(_data)
        self.assertEqual(_data.get("freight_code"), _freight_code)
        self.assertEqual(_data.get("goods_freight_money"), _goods_freight_money)
        self.assertEqual(_data.get("goods_less_count"), _goods_less_count)
        self.assertEqual(
            _data.get("goods_recycle_less_money"), _goods_recycle_less_money
        )
        self.assertEqual(_data.get("hidden_box_consume"), _hidden_box_consume)
        self.assertEqual(_data.get("name"), _name)
        self.assertEqual(_data.get("recharge_page_switch"), _recharge_page_switch)
        self.assertEqual(
            _data.get("statistical_exclude_user_id"), _statistical_exclude_user_id
        )

    def test_user_order_data(self):
        """用户消费记录"""
        admin_login(self.admin_c)
        create_orders()
        res = self.admin_c.get(
            "/api/admin/user/record/expense", {"user_uuid": self.user_s.data["uuid"]}
        )
        _data = self.assertOk(res)
        pprint(_data)
        user_order = UserOrder.objects.filter(deleted=False).first()
        res = self.admin_c.get(
            "/api/admin/user/record/expense/goods", {"order_uuid": user_order.uuid}
        )
        _data = self.assertOk(res)
        pprint(_data)
        goods = JuqiGood.objects.filter(deleted=False).first()
        res = self.admin_c.get(
            "/api/admin/user/record/expense/goods", {"order_uuid": user_order.uuid}
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_refined_user_order_goods(self):
        create_orders()
        goods = JuqiGood.objects.filter(deleted=False).first()
        _all = UserRefinedOrder.objects.filter(deleted=False).all()
        # for o in _all:
        #     pprint(UserOrderRefinedSerializer(o).data)

    def test_user_record_raffle(self):
        """抽赏记录"""
        admin_login(self.admin_c)
        create_orders()
        res = self.admin_c.get("/api/admin/user/record/raffle")
        _data = self.assertOk(res)
        pprint(_data)

        res = self.admin_c.get(
            "/api/admin/user/record/raffle", {"uid": self.user_s.data["id"]}
        )
        _data = self.assertOk(res)
        pprint(_data)
        user_order = UserOrder.objects.filter(deleted=False).first()
        res = self.admin_c.get(
            "/api/admin/user/record/raffle/goods", {"order_uuid": user_order.uuid}
        )
        _data = self.assertOk(res)
        pprint(_data)
        goods = JuqiGood.objects.filter(deleted=False).first()
        res = self.admin_c.get(
            "/api/admin/user/record/raffle/goods", {"order_uuid": user_order.uuid}
        )
        _data = self.assertOk(res)
        # pprint(_data)

    def test_get_game_num(self):
        admin_login(self.admin_c)
        create_orders()
        oder = UserOrder.objects.filter(deleted=False).first()
        # order_data = UserExpenseRecordSerializer(oder).data
        # res = self.admin_c.get(
        #     "/api/admin/user/record/purchase/game/num",
        #     {
        #         "game_type": order_data["game_type"],
        #         "game_uuid": order_data["game_uuid"],
        #     },
        # )
        # _data = self.assertOk(res)
        # pprint(_data)

    def test_user_record_refined(self):
        """
        测试用户提炼记录
        """
        admin_login(self.admin_c)
        create_orders()
        res = self.admin_c.get(
            "/api/admin/user/record/refined",
            {
                "name": "",
                "page": 1,
                "page_size": 5,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_record_refined_goods(self):
        admin_login(self.admin_c)
        create_orders()
        user_order_refined = UserRefinedOrder.objects.filter(deleted=False).first()

        res = self.admin_c.get(
            "/api/admin/user/record/refined/goods",
            {"order_refined_uuid": user_order_refined.uuid},
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_user_record_purchase_goods(self):
        # 购买记录
        admin_login(self.admin_c)
        create_orders()
        goods = JuqiGood.objects.filter(deleted=False).first()
        game = QuanjushangGame.objects.filter(deleted=False).first()
        game = QuanjushangGamSer(game).data
        res = self.admin_c.get(
            "/api/admin/user/record/purchase/goods",
            {
                "game_uuid": game["uuid"],
                "game_type": GameType.wuxianshang.value,
                "box_num": 1,
                "uid": 12222,
            },
        )
        _data = self.assertOk(res)
        pprint(_data)
        res = self.admin_c.get(
            "/api/admin/user/record/purchase/goods",
            {
                "game_uuid": game["uuid"],
                "game_type": GameType.quanjushang.value,
                "box_num": 1,
                # "uid": self.user_s.data["id"],
                "date_start": "2023-03-07",
            },
        )
        _data = self.assertOk(res)
        pprint(_data)
        res = self.admin_c.get(
            "/api/admin/user/record/purchase/goods",
            {
                "game_uuid": game["uuid"],
                "box_num": 1,
                "game_type": GameType.quanjushang.value,
                "date_end": "2023-03-07",
            },
        )
        _data = self.assertOk(res)
        pprint(_data)
        res = self.admin_c.get(
            "/api/admin/user/record/personal/details",
            {
                "game_uuid": game["uuid"],
                "box_num": 1,
                "game_type": GameType.quanjushang.value,
                "date_end": "2023-03-11",
            },
        )
        _data = self.assertOk(res)
        pprint(_data)

    def test_game_rule(self):
        admin_login(self.admin_c)
        res = self.admin_c.post(
            "/api/admin/roule",
            {
                "key": "mmmmkkk",
                "body": "testssssss",
                "type": 0,
            },
            content_type="application/json",
        )
        data = self.assertOk(res)
        pprint(data)
        uuid = data["data"]["uuid"]
        res = self.admin_c.put(
            "/api/admin/roule",
            {
                "uuid": uuid,
                "key": "mmk",
                "body": "1212121212",
                "type": 0,
            },
            content_type="application/json",
        )
        data = self.assertOk(res)
        pprint(data)
        res = self.admin_c.get(
            "/api/admin/roule/options",
        )
        data = self.assertOk(res)
        pprint(data)
        res = self.admin_c.get(
            "/api/admin/roule",
            {
                "uuid": uuid,
            },
        )
        data = self.assertOk(res)
        pprint(data)

        res = self.admin_c.delete(
            "/api/admin/roule?uuid=" + str(uuid),
        )
        data = self.assertOk(res)
        pprint(data)

        res = self.admin_c.get(
            "/api/admin/roule",
            {
                "uuid": uuid,
            },
        )
        self.assertError(res, GameRuleNullErr.code, GameRuleNullErr.msg)

        res = self.admin_c.get(
            "/api/admin/roule/list",
        )
        data = self.assertOk(res)
        pprint(data)

    def assertOk(self, res):
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        data: dict = json.loads(res.content)
        _code = data.get("code")
        self.assertIsNotNone(_code)
        _msg = data.get("msg")
        self.assertIsNotNone(_msg)
        self.assertEqual(_code, 0)
        self.assertEqual(_msg, "ok")
        return data

    def assertError(self, res, code, msg):
        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)
        data: dict = json.loads(res.content)

        _code = data.get("code")
        self.assertIsNotNone(_code)
        _msg = data.get("msg")
        self.assertIsNotNone(_msg)

        self.assertEqual(_code, code)
        self.assertEqual(_msg, msg)


# python manage.py test  juqiadmin.tests.JuqiAdminUserTest
class JuqiAdminUserTest(TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.c = Client()

    def test_query_admin_finance(self):
        # 登录管理员
        admin_login(self.c)

        #  query game finance
        get_game_finance(GameType.wuxianshang)
        get_game_finance(GameType.quanjushang)

        r = self.c.get(f"/api/admin/finance?finance_type={FinanceType.game.name}")
        self.assertEqual(r.status_code, status.HTTP_200_OK)

        d = json.loads(r.content)

        self.assertEqual(d.get("sum_count"), 2)

        # query wxuser
        wxuser_count = 51
        game = QuanjushangGame.objects.create(
            name="test池子", cover_url="123", user_limit=1, price=10, game_num=50
        )
        for _ in range(wxuser_count):
            get_wxuser_finance(
                user_uuid=uuid4(), gameType=GameType.quanjushang, game_uuid=game.uuid
            )

        r = self.c.get(f"/api/admin/finance?finance_type={FinanceType.wxuser.name}")
        self.assertEqual(r.status_code, status.HTTP_200_OK)

        d = json.loads(r.content)

        self.assertEqual(d.get("sum_count"), wxuser_count)


def mock_date(year=None, month=None, day=None):
    _date = datetime.datetime.today()
    _year = randint(2000, _date.year) if year is None else year
    _month = randint(1, 12) if month is None else month
    _day = randint(1, monthrange(_year, _month)[1]) if day is None else day
    return datetime.date(_year, _month, _day)


def mock_datetime(
    year=None,
    month=None,
    day=None,
    hour=None,
    minute=None,
    second=None,
    microsecond=None,
):
    _date = mock_date(year, month, day)
    _hour = randint(0, 23) if hour is None else hour
    _minute = randint(0, 59) if minute is None else minute
    _second = randint(0, 59) if second is None else second
    _microsecond = randint(0, 999999) if microsecond is None else microsecond
    return datetime.datetime(
        _date.year, _date.month, _date.day, _hour, _minute, _second, _microsecond
    )


def generate_db_user_list(size=1):
    user_list = []
    for i in range(size):
        user = Users(
            nickname=f"aabbccddeeff_{i}",
            openid=uuid4(),
        )
        user.save()
        user_list.append(user)
    return user_list


def generate_db_game_finance():
    game_types = [
        GameType.wuxianshang,
        GameType.quanjushang,
        GameType.wuxianshang_boss,
    ]
    for game_type in game_types:
        for i in range(randint(5, 20)):
            create_date = mock_datetime(2023)
            Finance(
                createdAt=create_date,
                finance_type=FinanceType.game.value,
                game_type=game_type.value,
            ).save()
